#include "game.h"

void menu()
{
	printf("--------------------------\n");
	printf("|         1.play         |\n");
	printf("|         0.exit         |\n");
	printf("--------------------------\n");
}

void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
	int i = 0;
	int j = 0;

	for (i = 0; i < rows; i++)
	{
		for (j = 0; j < cols; j++)
		{
			board[i][j] = set;
		}
	}
}

void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
	int i = 0;
	int j = 0;

	printf("-------扫雷游戏-------\n");

	for (i = 0; i <= row; i++)
	{
		printf("%d ", i);
	}

	printf("\n");

	for (i = 1; i <= row; i++)
	{
		printf("%d ", i);
		for (j = 1; j <= col; j++)
		{
			printf("%c ", board[i][j]);
		}
		printf("\n");
	}
}

void SetMine(char board[ROWS][COLS], int row, int col)
{
	int count = EASY_COUNT;
	while (count)
	{
		int x = rand() % row + 1;
		int y = rand() % col + 1;

		if (board[x][y] != '1')
		{
			board[x][y] = '1';
			count--;
		}
	}
}

int GetMineCount(char board[ROWS][COLS], int x, int y)
{
	int i = 0;
	int j = 0;
	int count = 0;

	for (i = -1; i <= 1; i++)
	{
		for (j = -1; j <= 1; j++)
		{
			count += board[x + i][y + j] - '0';
		}
	}
	return count;
}

//展开一片功能
void ExpendBoard(char board1[ROWS][COLS], char board2[ROWS][COLS], int x, int y)
{
	int i = 0;
	int j = 0;
	int count = 0;

	for (i = -1; i <= 1; i++)
	{
		for (j = -1; j <= 1; j++)
		{
			if (1 <= x+i && x + i <= 9 && 1 <= y + i && y + i <= 9)
			{
				if (board2[x + i][y + j] == '*')
				{
					count = GetMineCount(board1, x + i, y + j);
					board2[x + i][y + j] = count + '0';


					if (board2[x + i][y + j] == '0')
					{
						ExpendBoard(board1, board2, x + i, y + j);
					}

				}
			}
		}
	}
	
}


//board1真正的雷盘
void Demine(char board1[ROWS][COLS], char board2[ROWS][COLS], int row, int col)
{
	int x = 0;
	int y = 0;
	int count = 0;


	while (1)
	{
		printf("请输入你需要排查的坐标：\n");
		scanf("%d %d", &x, &y);

		if (x >= 1 && y >= 1 && x <= row && y <= col && board2[x][y] == '*')
		{
			if (board1[x][y] == '1')
			{
				printf("很遗憾你踩到雷了，你炸了，游戏失败\n");
				DisplayBoard(board1, ROW, COL);
				return;
			}
			else
			{
				count = GetMineCount(board1, x, y);

				board2[x][y] = count + '0';

				//展开一片
				if (board2[x][y] == '0')
				{
					ExpendBoard(board1, board2, x, y);
				}

				//改为空格
				for (int i = 1; i <= row; i++)
				{
					for (int j = 1; j <= col; j++)
					{
						if (board2[i][j] == '0')
						{
							board2[i][j] = ' ';
						}
					}
				}

			    //打印棋盘
				DisplayBoard(board2, ROW, COL);

				//判断是否胜出
				int game_count = 0;
				for (int i = 1; i <= row; i++)
				{
					for (int j = 1; j <= col; j++)
					{
						if (board2[i][j] == '*')
						{
							game_count++;
						}
					}
				}
				if (game_count == 10)
				{
					break;
				}
			}
		}
		else
		{
			printf("坐标非法，请重新输入：\n");
		}
	}
	printf("恭喜你，排雷成功！\n");
}
